<template>
  <div id="register">
    <LoginTop title="注册嗨皮happy">
      <div
        slot="right"
        class="slot"
        @click="
          () => {
            this.$router.push('/login');
          }
        "
      >
        切换到登录
      </div>
    </LoginTop>
    <LoginInput
      class="name"
      label="昵称"
      placeholder="请输入昵称"
      rule="^.{6,13}$"
      @sucessInput="sucessName"
    />
    <LoginInput
      label="账号"
      placeholder="请输入账号"
      rule="^.{6,13}$"
      @sucessInput="sucessUserName"
    />
    <LoginInput
      label="密码"
      type="password"
      placeholder="请输入密码"
      rule="^.{6,13}$"
      @sucessInput="sucessPassword"
    />
    <LoginButton text="注册" @submitClick="registerClick" />
  </div>
</template>

<script>
import LoginTop from "@/components/common/LoginTop.vue";
import LoginInput from "@/components/common/LoginInput.vue";
import LoginButton from "@/components/common/LoginButton.vue";

export default {
  components: {
    LoginTop,
    LoginInput,
    LoginButton,
  },
  data() {
    return {
      userinfo: {
        name: "",
        username: "",
        password: "",
      },
    };
  },
  methods: {
    sucessName(res) {
      this.userinfo.name = res;
    },
    sucessUserName(res) {
      this.userinfo.username = res;
    },
    sucessPassword(res) {
      this.userinfo.password = res;
    },
    registerClick() {
      if (!this.userinfo.name) {
        this.$toast.fail("昵称必须为6～13个字符");
      } else if (!this.userinfo.username) {
        this.$toast.fail("账号必须为6～13个字符");
      } else if (!this.userinfo.password) {
        this.$toast.fail("密码必须为6～13个字符");
      } else {
        this.submit();
      }
    },
    async submit() {
      let res = await this.$http.post("/register", this.userinfo);
      let data = res.data;
      this.$toast.fail(data.msg);
      if (data.code === 200) {
        /* 登录成功 内存保留用户数据 */
        localStorage.setItem("id", data.id);
        localStorage.setItem("token", data.objtoken);
        /* 1s后跳转个人中心 */
        setTimeout(() => {
          this.$router.replace("/userinfo");
        }, 1000);
      }
    },
  },
};
</script>

<style lang="less" scoped>
#register {
  .name {
    margin: 4.167vw 0;
  }
  .slot {
    font-size: 3.611vw;
    color: rgb(97, 96, 96);
  }
}
</style>
